package com.transaction.demo.consumer.mq;

import java.util.Map;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import com.google.gson.reflect.TypeToken;
import com.transaction.demo.common.enums.ResponseExceptionEnum;
import com.transaction.demo.common.util.JsonUtils;
import com.transaction.demo.common.util.Result;
import com.transaction.demo.message.MessageService;
import com.transaction.demo.message.TradePaymentManagerService;
import com.transaction.demo.trade.vo.req.CompletePayReqVo;

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "bank_notify", topic = "BANK_NOTIFY")
public class BankMessageListener implements RocketMQListener<String> {

	@Autowired(required = false)
	private TradePaymentManagerService managerService;

	@Autowired(required = false)
	private MessageService messageService;

	@Override
	public void onMessage(String s) {
		log.info("实时服务接收到银行回调消息：{}", s);

		Map<String, String> params = JsonUtils.fromJson(s, new TypeToken<Map<String, String>>() {
		}.getType());

		assert params != null;

		//完成交易
		CompletePayReqVo reqVo = new CompletePayReqVo();
		reqVo.setBusinessId(params.get("businessId"));
		reqVo.setStatus(params.get("status"));

		Result<String> result = managerService.completePay(reqVo);

		log.info("订单响应: {}", JsonUtils.toJson(result));
		if (result.getCode().equals(ResponseExceptionEnum.SUCCESS.getCode())) {
			//删除消息
			messageService.deleteMessageByMessageId(params.get("messageId"));
		}

	}
}
